define([
    'config',
    'angularAMD',
    'js/init',
    'metisMenu',
    'rcss!css/default'
], function(config, angularAMD) {
    var app = angular.module('app', ['app.main']);

    app.config(function($routeProvider, $httpProvider, cfpLoadingBarProvider) {
        $routeProvider.otherwise({
            redirectTo: config.defaultPath
        });

        // Loading bar's settings
        cfpLoadingBarProvider.includeBar = true;
        cfpLoadingBarProvider.includeSpinner = false;

        // http interceptor
        $httpProvider.interceptors.push(function($injector, $rootScope, $cookies) {
            return {
                responseError: function(rejection) {
                    if (!/^(http|https)/g.test(rejection.config.url)) {
                        // error
                        if (rejection.status == -1) {
                            $injector.get('xDialog').alert('错误信息', '服务器已断开连接或连接超时！');
                        } else if (rejection.status == 401) {
                            $rootScope.sessionUser = {};
                            $cookies.remove('session_user');
                            $injector.get('xDialog').open().showSecurity();
                        } else if (rejection.status == 403) {
                            $injector.get('xDialog').alert('提示信息', '您没有权限，请联系管理员！');
                        } else if (rejection.status >= 400) {
                            if (!/^\/mock\/test\//.test(rejection.config.url)) {
                                $injector.get('xDialog').alert('错误信息', rejection.data);
                            }
                        }
                    }
                    return rejection;
                }
            };
        });
    });

    app.run(function($http, $rootScope, $route, $timeout, $location, $cookies, $uibModalStack, xDialog, toastr) {
        var initialized = false;
        $rootScope.accessible = false;
        $rootScope.breadcrumb = '';
        // Session user
        var sessionUser = $cookies.getObject('session_user');
        if (sessionUser) {
            $rootScope.sessionUser = sessionUser;
            $rootScope.accessible = true;
        }
        // Check and reload session user
        $http.get('/mock/auth/rememberme').then(function(response) {
            if (response.status == 200) {
                sessionUser = response.data;
                $rootScope.accessible = response.data['accessible'];
                if (!response.data['accessible']) {
                    xDialog.open().showSecurity();
                }
            }
            // Update session user
            $rootScope.sessionUser = sessionUser;
            if (sessionUser.email) {
                $cookies.putObject('session_user', sessionUser);
            } else {
                $cookies.remove('session_user');
            }
            initialized = true;
        });

        // Override location path
        var original = $location.path;
        $location.path = function(path, reload) {
            if (reload === false) {
                var lastRoute = $route.current;
                var un = $rootScope.$on('$locationChangeSuccess', function() {
                    $route.current = lastRoute;
                    un();
                });
            }
            return original.apply($location, [path]);
        }

        $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
            $rootScope.routeName = current.$$route.name;
            $uibModalStack.dismissAll();
            if ($rootScope.accessible) {
                $rootScope.highlightMenus();
            } else if (initialized) {
                xDialog.open().showSecurity();
            }
        }); 

        // Resize page scope
        var callbacks = {};
        var resizePageScope = function(refreshable) {
            var viewHeight = Math.max($(window).height(), 700) - 51;
            var maxHeight = viewHeight - 30,
                maxWidth = Math.max($(window).width(), 1200);
            $('.x-container').css('height', viewHeight + 'px');
            $('.x-view-scope').css('height', maxHeight + 'px');
            $('.x-view-scope .x-editor pre').css('min-height', maxHeight + 'px');
            // Callback
            if (typeof(callbacks[$rootScope.routeName]) === 'function') {
                callbacks[$rootScope.routeName](maxHeight, maxWidth, refreshable);
            }
        };
        $rootScope.refresh = function(callback) {
            callbacks[$rootScope.routeName] = callback;
            $timeout(function() {
                $('.navbar-form').empty();
                resizePageScope(true);
            });
        };
        $(window).bind('load resize', function() {
            resizePageScope(false);
        });

        // Highlight sidebar
        $rootScope.highlightMenus = function() {
            $('#side-menu li').each(function() {
                var $this = $(this);
                var $link = $this.find('> a');
                var href = $link.attr('href').replace(/^#!/, '');
                if ($location.path().indexOf(href) >= 0) {
                    $('#side-menu li').removeClass('mm-active');
                    $this.addClass('mm-active');
                    $rootScope.breadcrumb = $link.text();
                    var $parent = $this.parent('ul');
                    if ($parent.length > 0) {
                        $parent.addClass('mm-show');
                        $parent = $parent.parent('li');
                        if ($parent.length > 0) {
                            $parent.addClass('mm-active');
                        }
                    }
                }
            });
        };

        // Initialize menu
        $rootScope.init = function() {
            $timeout(function() {
                // toggle
                if ($cookies.get('mini_menu')) {
                    $('body').addClass('mini');
                }
                $('.x-sidebar-toggle').click(function() {
                    if ($('body').hasClass('mini')) {
                        $('body').removeClass('mini');
                        $cookies.remove('mini_menu');
                    } else {
                        $('body').addClass('mini');
                        $cookies.put('mini_menu', true);
                    }
                });
                // metisMenu
                $('#side-menu').metisMenu({
                    toggle: true
                }).show();
                // highlight
                $rootScope.highlightMenus();
            }, 50);
        }

        // Security
        $rootScope.login = function() {
            xDialog.open().showSecurity();
        }
        $rootScope.editPassword = function() {
            xDialog.open().editPassword();
        }
        $rootScope.showToken = function() {
            xDialog.open().showToken();
        }
        $rootScope.logout = function() {
            $http.post('/mock/auth/logout').then(function(response) {
                if (response.status == 200) {
                    $rootScope.sessionUser = {};
                    $cookies.remove('session_user');
                    toastr.success('用户退出成功！');
                    // Check access
                    $rootScope.accessible = response.data['accessible'];
                    if (!response.data['accessible']) {
                        xDialog.open().showSecurity();
                    }
                }
            });
        }
    });

    return angularAMD.bootstrap(app);
});
